package com.megalith.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import com.megalith.dto.ActivityRebackDTO;
import com.megalith.dto.TaskAssignDTO;
import com.megalith.service.CommonTaskService;
import com.megalith.vo.*;
import org.flowable.engine.HistoryService;
import org.flowable.engine.IdentityService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.flowable.engine.history.HistoricActivityInstance;
import org.flowable.engine.history.HistoricDetail;
import org.flowable.engine.task.Comment;
import org.flowable.idm.api.Group;
import org.flowable.task.api.Task;
import org.flowable.task.api.history.HistoricTaskInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description TODO
 * @Author lfp
 * @Date 2022/7/17
 * @Version 1.0
 */
@Service
public class CommonTaskServiceImpl implements CommonTaskService {
    @Autowired
    private TaskService taskService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private HistoryService historyService;
    @Autowired
    private IdentityService identityService;

    @Override
    public TaskEntityVO queryProcessCurrentTask(String processInstanceId) {
        Task task = taskService.createTaskQuery()
                .processInstanceId(processInstanceId)
                .active()
                .singleResult();
        return BeanUtil.copyProperties(task,TaskEntityVO.class);
    }

    @Override
    public List<TaskEntityVO> listPersonalCandidateTask(String userId) {
        //查询可认领的个人任务
        List<Task> list = taskService.createTaskQuery()
                .taskCandidateUser(userId)
                .active()
                .list();

        //可领取的组任务查询
        Group group = identityService.createGroupQuery()
                .groupMember(userId)
                .singleResult();
        if(group != null){
            Task groupTask = taskService.createTaskQuery()
                    .taskCandidateGroup(group.getId())
                    .active()
                    .singleResult();
            if(groupTask != null){
                list.add(groupTask);
            }
        }

        //处理所有可领取的任务
        List<TaskEntityVO> taskEntityVOList = list.stream().map(task -> {
            return BeanUtil.copyProperties(task, TaskEntityVO.class);
        }).collect(Collectors.toList());

        return taskEntityVOList;
    }

    @Override
    public List<HistoricTaskInstanceVO> queryHistoricTaskInfoList(String processInstanceId) {
        //查找历史任务信息
        List<HistoricTaskInstance> historicTaskInstanceList = historyService.createHistoricTaskInstanceQuery()
                .processInstanceId(processInstanceId)//流程实例编号
                //.processFinished()//仅选择作为已完成流程实例的历史任务实例。未结束的流程无法查询
                .orderByTaskId()
                .desc()
                .orderByHistoricTaskInstanceEndTime()
                .desc()
                .list();

        List<HistoricTaskInstanceVO> historicTaskInstanceVOList = historicTaskInstanceList.stream().map(task -> {
            HistoricTaskInstanceVO historicTaskInstanceVO = BeanUtil.copyProperties(task, HistoricTaskInstanceVO.class);
            historicTaskInstanceVO.setTaskId(task.getId());

            historicTaskInstanceVO.setStartTime(DateUtil.formatDateTime(task.getStartTime()))
                    .setEndTime(DateUtil.formatDateTime(task.getEndTime()));

            List<Comment> taskComments = taskService.getTaskComments(task.getId());
            historicTaskInstanceVO.setComments(taskComments);

            return historicTaskInstanceVO;
        }).collect(Collectors.toList());



        return historicTaskInstanceVOList;
    }

    @Override
    public List<HistoricActivityInstanceEntityVO> queryHistoricActivityInfoList(String processInstanceId) {
        //历史活动信息
        List<HistoricActivityInstance> historicActivityInstanceList = historyService.createHistoricActivityInstanceQuery()
                .processInstanceId(processInstanceId)
                //endEvent startEvent userTask
                //.activityType("userTask")
                .orderByHistoricActivityInstanceStartTime()
                .finished()//仅查询已处理（完成）的活动
                .desc()
                .list();

        List<HistoricActivityInstanceEntityVO> historicActivityInstanceEntityVOList = historicActivityInstanceList.stream().filter(activity ->{
            if(!activity.getActivityType().equals("startEvent") &&
                    !activity.getActivityType().equals("endEvent") &&
                    !activity.getActivityType().equals("userTask")){
                return false;
            }
            return true;
        }).map(activity -> {

            //历史活动基本属性拷贝
            HistoricActivityInstanceEntityVO historicActivityInstanceEntityVO = BeanUtil.copyProperties(activity, HistoricActivityInstanceEntityVO.class);

            historicActivityInstanceEntityVO.setStartTime(DateUtil.formatDateTime(activity.getStartTime()))
                    .setEndTime(DateUtil.formatDateTime(activity.getEndTime()));

            //查询活动相关流程变量
            List<HistoricDetail> historicDetailList = historyService.createHistoricDetailQuery()
                    .processInstanceId(activity.getProcessInstanceId())
                    .activityInstanceId(activity.getId())
                    .list();
            if (historicDetailList.size() > 0) {
                List<HistoricDetailVariableInstanceVO> variableList = new ArrayList();
                for (HistoricDetail historicDetail : historicDetailList) {
                    variableList.add(BeanUtil.copyProperties(historicDetail, HistoricDetailVariableInstanceVO.class));
                }
                //设置活动相关流程变量
                historicActivityInstanceEntityVO.setVariableList(variableList);
            }

            List<Comment> taskComments = taskService.getTaskComments(activity.getTaskId());
            historicActivityInstanceEntityVO.setComments(taskComments);

            return historicActivityInstanceEntityVO;
        }).collect(Collectors.toList());

        return historicActivityInstanceEntityVOList;
    }

    @Override
    public Result assignTaskToOthers(TaskAssignDTO taskAssignDTO) {
        Task task = taskService.createTaskQuery()
                .processInstanceId(taskAssignDTO.getProcessInstanceId())
                .taskAssignee(taskAssignDTO.getCurrentUserId())
                .active()
                .singleResult();

        if(task == null){
            return Result.sysError("未查询到相关任务");
        }

        taskService.setAssignee(task.getId(),taskAssignDTO.getTargetUserId());

        return Result.ok("任务指派成功!");
    }

    @Override
    public void processActivityReback(ActivityRebackDTO rebackDTO) {
        //根据流程实例ID，将当前请假流程，退回到指定节点
        runtimeService.createChangeActivityStateBuilder()
                .processInstanceId(rebackDTO.getProcessInstanceId())
                .moveActivityIdTo(rebackDTO.getCurrentActivityId(),rebackDTO.getNewActivityId())
                .changeState();
    }

    @Override
    public List<TaskEntityVO> listPersonalAssignmentTask(String userId) {
        List<Task> list = taskService.createTaskQuery()
                .taskCandidateOrAssigned(userId)//可认领或已分配的个人任务
                .active()
                .orderByTaskCreateTime()
                .asc()
                .list();

        List<TaskEntityVO> taskEntityVOList = list.stream().map(task -> {
            TaskEntityVO taskEntityVO = BeanUtil.copyProperties(task, TaskEntityVO.class);
            taskEntityVO.setTaskId(task.getId());

            return taskEntityVO;
        }).collect(Collectors.toList());

        return taskEntityVOList;
    }
}
